//
//  YTCitySeletedViewModel.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/12.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTCitySeletedViewModel.h"
#import "YTSeletedServices.h"
#import "YTCityModel.h"
#import "YTCountryModel.h"

@interface YTCitySeletedViewModel ()

@property (strong, nonatomic, readwrite) RACCommand *showCityCommand;

@property (strong, nonatomic, readwrite) RACSignal *searchSignal;
@property (strong, nonatomic, readwrite) RACCommand *loadDataCommand;
@property (strong, nonatomic, readwrite) RACCommand *searchCommand;
@property (strong, nonatomic, readwrite) RACCommand *deleteCommand;

@end

@implementation YTCitySeletedViewModel

- (void)initialize {
    // 初始化
    _dataDict = [NSMutableDictionary dictionary];
    _keyArray = [NSMutableArray array];
    _searchArray = [NSMutableArray array];
    _selectArray = [NSMutableArray array];
    _deleteArray = [NSMutableArray array];
    _cityArray = [NSMutableArray array];
    _selectIDArray = [NSMutableArray array];
    
    // 从网络加载数据
    [self loadDataFromServer];
    
    // 搜索城市逻辑
    [self searchCity];
    
    // 顶部删除和添加选中城市
    [self deleteSelectedCity];
    
    // 显示城市tableView
    [self showCityTable];
}

#pragma mark - 从网络加载数据

- (void)loadDataFromServer {
    @weakify(self);
    _loadDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [[YTSeletedServices loadCountryList] subscribeNext:^(NSDictionary *response) {
                if ([response[@"resultCode"] integerValue] == 1000) {
                    @strongify(self);
                    NSDictionary *dict = response[@"responseData"];
                    if (self.isInland) {
                        NSArray<YTCountryModel *> *inland = [NSArray yy_modelArrayWithClass:[YTCountryModel class] json:dict[@"provinceList"]];
                        [self loadKeyArray:inland];
                        [self sortData:inland subscriber:subscriber];
                    } else {
                        NSArray<YTCountryModel *> *international = [NSArray yy_modelArrayWithClass:[YTCountryModel class] json:dict[@"countryList"]];
                        [self loadKeyArray:international];
                        [self sortData:international subscriber:subscriber];
                    }
                }
            }];
            
            return [RACDisposable disposableWithBlock:^{}];
        }];
    }];
}

- (void)loadKeyArray:(NSArray<YTCountryModel *> *)countryArray {
    for (YTCountryModel *model in countryArray) {
        if (![self.keyArray containsObject:model.firstChar]) {
            [self.keyArray addObject:model.firstChar];
        }
    }
}

#pragma mark - 搜索城市逻辑

- (void)searchCity {
    @weakify(self);
    RACSignal *searchSignal = [[[[self rac_signalForSelector:@selector(searchBar:textDidChange:)
                                                fromProtocol:@protocol(UISearchBarDelegate)] doNext:^(RACTuple *tuple) {
        @strongify(self);
        self.isSearch = YES;
        [self.searchArray removeAllObjects];
        for (NSArray<YTCityModel *> *array in self.dataDict.allValues) {
            for (YTCountryModel *countryModel in array) {
                for (YTCityModel *model in countryModel.cityList) {
                    if ([model.nameEn containsString:tuple.last] || [model.name containsString:tuple.last]) {
                        [self.searchArray addObject:model];
                    }
                }
            }
        }
    }] replayLazily] mapReplace:@(YES)];
    
    RACSignal *cancleSignal = [[[[self rac_signalForSelector:@selector(searchBarCancelButtonClicked:)
                                                fromProtocol:@protocol(UISearchBarDelegate)] doNext:^(id x) {
        @strongify(self);
        self.isSearch = NO;
        [self.searchArray removeAllObjects];
    }] replayLazily] mapReplace:@(NO)];
    _searchSignal = [searchSignal merge:cancleSignal];
}

#pragma mark - 删除选中的城市

- (void)deleteSelectedCity {
    @weakify(self);
    self.didSelectItemCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(YTCityModel *cityModel) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            [self.selectArray addObject:cityModel.name];
            [self.selectIDArray addObject:cityModel.cityId];
            [subscriber sendNext:self.selectArray];
            [subscriber sendCompleted];
            return nil;
        }];
    }];
    
    _deleteCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSArray<NSString *> *deleteArray) {
        @strongify(self);
        [self.selectArray removeObjectsInArray:self.deleteArray];
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [subscriber sendNext:self.selectArray];
            [subscriber sendCompleted];
            return nil;
        }];
    }];
}

#pragma mark - 显示城市列表

- (void)showCityTable {
    _showCityCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSArray<YTCityModel *> *cityArray) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [self.cityArray removeAllObjects];
            [self.cityArray addObjectsFromArray:cityArray];
            [subscriber sendNext:cityArray];
            [subscriber sendCompleted];
            return nil;
        }];
    }];
}

#pragma mark - Private

- (void)sortData:(NSArray<YTCountryModel *> *)array subscriber:(id<RACSubscriber>)subscriber {
    for (NSString *str in self.keyArray) {
        NSMutableArray *temp = [NSMutableArray array];
        for (YTCountryModel *model in array) {
            if ([model.firstChar isEqualToString:str]) {
                [temp addObject:model];
            }
        }
        
        if (temp.count != 0) {
            [self.dataDict setObject:temp forKey:str];
        }
    }
    
    RACTuple *tuple = RACTuplePack(self.keyArray, self.dataDict);
    
    [subscriber sendNext:tuple];
    [subscriber sendCompleted];
}

@end
